import Taro from "@tarojs/taro";
import { Iapi } from "./interface";
import Config from "./Config";

export const key = "09ddf08a509b9cb8222a5f9daa3bb536";

export function request<T>(api: Iapi, data: any = {}, fin?: () => any) {
  const { url, method } = api;
  return new Promise<T>(function(resolve, reject) {
    // resolve('123');
    const myData = data; // api.method === 'POST' ? Qs.stringify(data) : data;
    if (api.needKey) {
      myData.key = key;
    }
    const header =
      api.method === "POST"
        ? {
            "Content-Type": "application/x-www-form-urlencoded"
          }
        : {};

    Taro.request<string>({
      url: Config.host + Config.baseURL + url,
      method,
      data: myData,
      header,
      dataType: "其他",
      responseType: "text"
    })
      .catch(error => {
        Taro.showModal({
          title: "请求错误",
          content: JSON.stringify(error)
        });
        fin && fin();
        reject();
      })
      .then(callback => {
        fin && fin();
        if (callback) {
          //   console.log("callback.data", callback);

          try {
            resolve(
              (api.dataType === "其他"
                ? callback.data
                : JSON.parse(callback.data)) as T
            );
          } catch (e) {
            Taro.showModal({
              title: "请求数据错误",
              content: `${e}\n\n${callback.data}`
            });
          }
        } else {
          reject();
        }
      });
  });
}
